<template>
	<view class="content">
		<view class="pageArea">
			<view class="tipText">
				请在虚线内进行书写
			</view>
			<view class="writeArea">
				<canvas class="writeInner" canvas-id="writeCanvas" :disable-scroll="true" @touchstart="uploadScaleStart"
					@touchmove="uploadScaleMove"></canvas>
			</view>
		</view>
		<view class="bottomArea">
			<view class="btn" @tap="retDraw">
				清除
			</view>
			<view class="btn" @tap="saveCanvasAsImg">
				确定
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				canvasName: 'writeCanvas',
				ctx: '',
				startX: null,
				startY: null,
				canvasWidth: 0,
				canvasHeight: 0,
				selectColor: 'black',
				lineColor: '#1A1A1A', // 颜色
				lineSize: 5, // 笔记倍数
				name: '', //用来区分多个签字
			}
		},
		onLoad() {

		},
		onReady() {
		    this.$nextTick(() => {
		      this.name = 'handWriting1'
		      this.ctx = uni.createCanvasContext("writeCanvas");
		      this.$nextTick(() => {
		        uni.createSelectorQuery().select('.writeArea').boundingClientRect(rect => {
		          this.canvasWidth = rect.width;
		          this.canvasHeight = rect.height;
		          /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
		          this.setCanvasBg('#fff');
		        }).exec();
		      });
		    })
		  },
		methods: {

			// 笔迹开始
			uploadScaleStart(e) {
				this.startX = e.changedTouches[0].x
				this.startY = e.changedTouches[0].y
				//设置画笔参数
				//画笔颜色
				this.ctx.setStrokeStyle(this.lineColor)
				//设置线条粗细
				this.ctx.setLineWidth(this.lineSize)
				//设置线条的结束端点样式
				this.ctx.setLineCap("round") //'butt'、'round'、'square'
				//开始画笔
				this.ctx.beginPath()
			},
			// 笔迹移动
			uploadScaleMove(e) {
				//取点
				let temX = e.changedTouches[0].x
				let temY = e.changedTouches[0].y
				//画线条
				this.ctx.moveTo(this.startX, this.startY)
				this.ctx.lineTo(temX, temY)
				this.ctx.stroke()
				this.startX = temX
				this.startY = temY
				this.ctx.draw(true)
			},
			/**
			 * 重写
			 */
			retDraw() {
				if (this.startX == null && this.startY == null) {
					return;
				}
				this.ctx.clearRect(0, 0, 700, 730);
				this.ctx.draw();
				//设置canvas背景
				this.setCanvasBg('#fff');
				this.startX = null;
				this.startY = null;
			},


			//生成图片
			async saveCanvasAsImg() {
				if (this.startX == null && this.startY == null) {
					return;
				}
				uni.showLoading({
					mask: true
				})
				var res = await uni.canvasToTempFilePath({
					canvasId: 'writeCanvas',
					fileType: 'png',
					quality: 1, //图片质量
				});
				for (var i = 0; i < res.length; i++) {
					if (res[i] && res[i].tempFilePath) {
						res = await this.nupload(res[i].tempFilePath, 14);
						break;
					}
				}
				// res = await this.nupload(path, 13);
				uni.hideLoading();
				uni.showToast({
					title: "已上传"
				})
			},

			//设置canvas背景色  不设置  导出的canvas的背景为透明
			//@params：字符串  color
			setCanvasBg(color) {

				/* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
				//rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
				//这里是 canvasHeight - 4 是因为下边盖住边框了，所以手动减了写
				this.ctx.rect(0, 0, this.canvasWidth, this.canvasHeight - 4);
				// ctx.setFillStyle('red')
				this.ctx.setFillStyle(color);
				this.ctx.fill(); //设置填充
				this.ctx.draw(); //开画
			},
			// 上传图片并返回上传结果
			async nupload(filePath, imgType) {
				if (!filePath) return; //如果 filePath 不存在，直接返回

				// 调用 postWaitWorkImage 方法发送 POST 请求上传图片，并传递了文件路径、参数等信息。
				// 若上传成功，将返回结果解析为 JSON 格式（如果不是JSON格式，则直接使用原始结果）。



				const res = await postWaitWorkImage({
					filePath,
					name: "file",
					params: {
						imgType,
						id: this.merInfo.id,
					},
				}).catch((e) => (console.log(e), false));
				let res_;
				try {
					res_ = JSON.parse(res);
				} catch {
					res_ = res;
				}

				if (res_.code === 200) {
					return res_;
				} else {
					uni.showToast({
						title: "上传失败",
						icon: "error"
					});
					return false;
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.pageArea {
			margin: 20rpx auto;
			width: 90%;
			height: calc(100vh - 140rpx);

			.tipText {
				font-size: 28rpx;
				color: tomato;
			}

			.writeArea {
				margin-top: 20rpx;
				height: calc(100% - 40px);
				border: 1rpx dashed orange;
				border-radius: 8rpx;

				.writeInner {
					width: 100%;
					height: 100%;
				}
			}
		}

		.bottomArea {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 100rpx;
			display: flex;
			justify-content: space-around;
			align-items: center;
			box-shadow: 0 -2px 4px 2px rgba(0, 0, 0, .18);

			.btn {
				padding: 0 40rpx;
				height: 60rpx;
				line-height: 60rpx;
				font-size: 28rpx;
				border: 1px solid blue;
				border-radius: 12rpx;
			}
		}
	}
</style>